package org.linlinjava.litemall.admin.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.service.AdminVendorService;
import org.linlinjava.litemall.admin.service.LogHelper;
import org.linlinjava.litemall.admin.vo.VendorRegVo;
import org.linlinjava.litemall.core.util.RegexUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.Vendor;
import org.linlinjava.litemall.db.domain.VendorEmployee;
import org.linlinjava.litemall.db.service.LitemallAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.*;

@RestController
@RequestMapping("/admin/vendor")
@Validated
public class AdminVendorController {
    private final Log logger = LogFactory.getLog(AdminVendorController.class);

    @Autowired
    private AdminVendorService vendorService;
    @Autowired
    private LitemallAdminService adminService;
    @Autowired
    private LogHelper logHelper;

    @RequiresPermissions("admin:vendor:list")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String vendorCode, String vendorName, @RequestParam(defaultValue = "0") Integer status,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<Vendor> vendorList = vendorService.query(vendorCode, vendorName, status, page, limit, sort, order);
        return ResponseUtil.okList(vendorList);
    }

    private Object validate(Vendor vendor) {
        String name = vendor.getVendorName();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }
        String code = vendor.getVendorCode();
        if (StringUtils.isEmpty(code)) {
            return ResponseUtil.badArgument();
        }
        return null;
    }

    @RequiresPermissions("admin:vendor:create")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody Vendor vendor) {
        Object error = validate(vendor);
        if (error != null) {
            return error;
        }
        vendorService.add(vendor);
        return ResponseUtil.ok(vendor);
    }

    @RequiresPermissions("admin:vendor:read")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "详情")
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        Vendor vendor = vendorService.findById(id);
        return ResponseUtil.ok(vendor);
    }

    @RequiresPermissions("admin:vendor:update")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody Vendor vendor) {
        Object error = validate(vendor);
        if (error != null) {
            return error;
        }
        if (vendorService.updateById(vendor) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok(vendor);
    }

    @RequiresPermissions("admin:vendor:approve")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺审核"}, button = "审核")
    @PostMapping("/approve")
    public Object approve(@RequestBody Vendor vendor) {
        Vendor v = new Vendor();
        v.setId(vendor.getId());
        v.setStatus(vendor.getStatus());
        v.setMemo(vendor.getMemo());
        if (vendorService.approve(v) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok(vendor);
    }

    @RequiresPermissions("admin:vendor:delete")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody Vendor vendor) {
        Integer id = vendor.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        vendorService.deleteById(id);
        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:vendor:getEmployees")
    @RequiresPermissionsDesc(menu = {"商铺管理", "店员管理"}, button = "查看")
    @GetMapping("/employees")
    public Object getEmployees(@NotNull Integer vendorId) {
        List<VendorEmployee> employees = vendorService.getEmployees(vendorId);
        return ResponseUtil.okList(employees);
    }
    @RequiresPermissions("admin:vendor:deleteEmployee")
    @RequiresPermissionsDesc(menu = {"商铺管理", "店员管理"}, button = "删除")
    @PostMapping("/deleteEmployee")
    public Object deleteEmployee(@RequestBody VendorEmployee employee) {
        Integer id = employee.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        vendorService.deleteEmployeeById(id);

        return ResponseUtil.ok();
    }
    @RequiresPermissions("admin:vendor:publishEmployee")
    @RequiresPermissionsDesc(menu = {"商铺管理", "店员管理"}, button = "新增")
    @PostMapping("/publishEmployee")
    public Object publishEmployee(@RequestBody VendorEmployee employee) {
        Object error = validateEmployee(employee, false);
        if (error != null) {
            return error;
        }

        List<LitemallAdmin> adminList = adminService.findAdmin(employee.getUsername());
        if (adminList.size() > 0) {
            return ResponseUtil.fail(ADMIN_NAME_EXIST, "此登陆账号已经存在");
        }

        if (!RegexUtil.isUsername(employee.getUsername())) {
            return ResponseUtil.fail(ADMIN_INVALID_NAME, "登陆账号不符合规定");
        }

        if(StringUtils.isEmpty(employee.getPassword())){
            return ResponseUtil.fail(ADMIN_INVALID_PASSWORD, "密码不能为空");
        }

        vendorService.addEmployee(employee);
        logHelper.logAuthSucceed("添加商铺管理员", employee.getUsername());

        return ResponseUtil.ok(employee);
    }

    @RequiresPermissions("admin:vendor:editEmployee")
    @RequiresPermissionsDesc(menu = {"商铺管理", "店员管理"}, button = "编辑")
    @PostMapping("/editEmployee")
    public Object editEmployee(@RequestBody VendorEmployee employee) {
        Object error = validateEmployee(employee, true);
        if (error != null) {
            return error;
        }
        employee.setUsername(null);
        if (vendorService.updateEmployeeById(employee) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok(employee);
    }

    @PostMapping("/register")
    public Object register(@RequestBody VendorRegVo regVo) {
        Object error = validateVendorRegVo(regVo);
        if (error != null) {
            return error;
        }
        vendorService.doReg(regVo);
        return ResponseUtil.ok(regVo);
    }
    private Object validateVendorRegVo(VendorRegVo regVo) {
        if (!regVo.isValid()) {
            return ResponseUtil.badArgument();
        }
        if(!adminService.findAdmin(regVo.getUsername()).isEmpty()) {
            return ResponseUtil.fail(401, regVo.getUsername() + "已被注册");
        }
        return null;
    }
    private Object validateEmployee(VendorEmployee employee, boolean isUpdate) {
        if (StringUtils.isEmpty(employee.getName())) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isEmpty(employee.getUsername())) {
            return ResponseUtil.badArgument();
        }
        if(!isUpdate && !adminService.findAdmin(employee.getUsername()).isEmpty()) {
            return ResponseUtil.fail(401, employee.getUsername() + "已被注册");
        }
        return null;
    }
}
